package main

import (
	"context"
	"errors"
	"fmt"
	"time"
)

///////////////////////////////////////////////////////
////////// UserTask

type UserTask struct {
	UserData string
}

func (this *UserTask) Callback(ctx context.Context) error {
	fmt.Println("Running Task:", this.UserData)
	return errors.New("Dummy Error")
}

func (this *UserTask) SlowCallback(ctx context.Context) error {
	fmt.Println("Running Very Slow Task:", this.UserData)

	/// Make Slow Job Slice
	for i := 0; i <= 10; i++ {
		time.Sleep(5 * time.Second)
		select {
		case <-ctx.Done():
			return ctx.Err()
		default:
		}
	}

	return nil
}

func (this *UserTask) TaskRunCallback()           { fmt.Println("Start Task") }
func (this *UserTask) TaskDoneCallback(err error) { fmt.Println("Done Task|Error", err) }
func (this *UserTask) TaskCancelCallback()        { fmt.Println("Cancel Task") }

///////////////////////////////////////////////////////
////////// UserTask

func main() {
	{
		ut := &UserTask{"Let's Rock"}

		t := NewCronTask(time.Now().Add(time.Second), ut.Callback)
		t.SetTaskRunCallback(ut.TaskRunCallback)
		t.SetTaskDoneCallback(ut.TaskDoneCallback)
		t.SetTaskCancelCallback(ut.TaskCancelCallback)

		u := AddTask(t)
		fmt.Println(u)
		time.Sleep(time.Second)
	}

	{
		ut := &UserTask{"Let's Slow Rock"}

		t := NewCronTask(time.Now().Add(time.Second*1), ut.SlowCallback)
		t.SetTaskRunCallback(ut.TaskRunCallback)
		t.SetTaskDoneCallback(ut.TaskDoneCallback)
		t.SetTaskCancelCallback(ut.TaskCancelCallback)

		u := AddTask(t)
		fmt.Println(u)

		time.Sleep(2 * time.Second) // make sure it in running

		CancelTask(u)
		fmt.Println("Called CancelTask")
		time.Sleep(10 * time.Second)
	}
}
